package com.example.springbootredis.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.eshop.entity.Cart;
import com.example.eshop.entity.Product;
import com.example.eshop.dto.CartDTO;
import com.example.eshop.mapper.CartMapper;
import com.example.eshop.mapper.ProductMapper;
import com.example.eshop.service.CartService;
import com.example.eshop.vo.CartVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional
    public void addToCart(CartDTO cartDto) {
        // 验证商品是否存在且上架
        Product product = productMapper.selectById(cartDto.getProductId());
        if (product == null || product.getStatus() != 1) {
            throw new RuntimeException("商品不存在或已下架");
        }

        // 验证库存（防止超卖）
        if (product.getStock() < cartDto.getQuantity()) {
            throw new RuntimeException("库存不足");
        }

        // 检查购物车是否已有该商品
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", cartDto.getUserId())
                .eq("product_id", cartDto.getProductId());
        Cart existingCart = cartMapper.selectOne(queryWrapper);

        if (existingCart != null) {
            // 更新数量，再次验证库存
            int newQuantity = existingCart.getQuantity() + cartDto.getQuantity();
            if (product.getStock() < newQuantity) {
                throw new RuntimeException("库存不足");
            }
            existingCart.setQuantity(newQuantity);
            cartMapper.updateById(existingCart);
        } else {
            // 新增购物车记录
            Cart cart = new Cart();
            BeanUtils.copyProperties(cartDto, cart);
            cart.setSelected(1); // 默认选中
            cartMapper.insert(cart);
        }
    }

    @Override
    public CartVO getCartList(Long userId) {
        List<Cart> cartList = cartMapper.selectCartWithProduct(userId);

        // 计算总金额和选中数量
        BigDecimal totalAmount = BigDecimal.ZERO;
        int selectedCount = 0;

        for (Cart cart : cartList) {
            if (cart.getSelected() == 1 && cart.getProductStatus() == 1) {
                BigDecimal itemTotal = cart.getProductPrice()
                        .multiply(BigDecimal.valueOf(cart.getQuantity()));
                totalAmount = totalAmount.add(itemTotal);
                selectedCount++;
            }
        }

        CartVO cartVO = new CartVO();
        cartVO.setCartList(cartList);
        cartVO.setTotalAmount(totalAmount);
        cartVO.setSelectedCount(selectedCount);

        return cartVO;
    }

    @Override
    @Transactional
    public void updateQuantity(CartDTO cartDto) {
        Cart cart = cartMapper.selectById(cartDto.getCartId());
        if (cart == null) {
            throw new RuntimeException("购物车记录不存在");
        }

        // 验证商品库存
        Product product = productMapper.selectById(cart.getProductId());
        if (product.getStock() < cartDto.getQuantity()) {
            throw new RuntimeException("库存不足");
        }

        cart.setQuantity(cartDto.getQuantity());
        cartMapper.updateById(cart);
    }

    @Override
    public void deleteCartItem(Long cartId) {
        cartMapper.deleteById(cartId);
    }

    @Override
    public void selectItem(Long cartId, Integer selected) {
        Cart cart = cartMapper.selectById(cartId);
        if (cart != null) {
            cart.setSelected(selected);
            cartMapper.updateById(cart);
        }
    }

    @Override
    public void selectAll(Long userId, Integer selected) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        List<Cart> cartList = cartMapper.selectList(queryWrapper);
        for (Cart cart : cartList) {
            cart.setSelected(selected);
            cartMapper.updateById(cart);
        }
    }
}